package com.student.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author lin945
 * @date 2020/4/25 14:33
 */
@WebFilter("/home")
public class homeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpSession session = request.getSession();
        Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("admin".equals(cookie.getName())) {
                        // 判断是否存在第一次登录时存放的cookie
                        if (session.getAttribute("username") != null) {
                            // 判断服务器里面的存放的cookie是否存在
                            filterChain.doFilter(servletRequest, servletResponse);
                            return;
                        }
                        request.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
                        return;
                    }
                }
            }
            request.getRequestDispatcher("/login").forward(servletRequest, servletResponse);
            return;

    }

    @Override
    public void destroy() {

    }
}
